package com.element.music.component.util;

import cn.hutool.core.io.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileUtils {


    /**
     * 下载文件
     * @param filename
     * @param res
     * @throws IOException
     */
    public static void download(String filename, HttpServletResponse res) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取filename
        bis = new BufferedInputStream(new FileInputStream(new File("./file/" + filename)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
    }

    /**
     * 上传文件
     * @param path 文件路径
     * @param multipartFile 文件
     * @return 文件最终的路径
     */
    public static String uploadFile(String path, MultipartFile multipartFile) {
        File touch = FileUtil.touch(path);
        File copy = FileUtil.copy((File) multipartFile, touch, false);
        return copy.getName();
    }

}
